<script setup>
import { onMounted, ref } from 'vue'
import { initMap } from './initMap'
import { getBoundary } from './getBoundary'
import { addMarker } from './addMarker'
import { getTypeAllAPI, getPointsAllAPI } from '@/apis/index'
import { arr2tree } from '@/utils/arr2tree'
import { generateRandomHexColor } from '@/utils/generateRandomHexColor'
import { ElLoading } from 'element-plus'

const loadingInstance = ElLoading.service()

// 获取分类列表
const typeList = ref([])
const getTypeAll = async () => {
  const res = await getTypeAllAPI()
  typeList.value = arr2tree(res.data.data)
  // 去掉中小河道
  const index = typeList.value.findIndex(obj => {
    console.log(obj.name)
    return obj.name === '中小河道'
  })
  typeList.value.splice(index, 1)
  // 末尾补充 2 个
  typeList.value = typeList.value.concat([
    {
      id: 99,
      name: '顺义区水系图',
      isMap: 0,
      ord: 22,
      pid: 0,
      children: [],
      contents: ''
    },
    {
      id: 66,
      name: '顺义区路网图',
      isMap: 0,
      ord: 22,
      pid: 0,
      children: [],
      contents: ''
    }
  ])
  console.log(typeList.value)
  addColor(res.data.data)
}

// 获取总列表
const pointsTableList = ref([])

// 给二级分类配色
const addColor = (typeList) => {
  const secondTypeList = typeList.filter((type) => type.pid !== 0)
  const colorList = generateRandomHexColor(secondTypeList.length)
  secondTypeList.forEach((type, index) => {
    type.color = colorList[index]
  })
}

// 匹配三级分类（具体point节点）
const formatTypeList = () => {
  pointsTableList.value.forEach((point) => {
    typeList.value.forEach((type) => {
      const targetTypeObj = type.children.find(
        (item) => item.id === point.typeId
      )
      if (targetTypeObj) {
        targetTypeObj.children.push(point)
      }
    })
  })
}

const getPointsAll = async () => {
  const res = await getPointsAllAPI()
  pointsTableList.value = res.data.data
  await getTypeAll()
  formatTypeList()
  // 初始化首次激活
  switchType(typeList.value[0])
}


// 切换左侧分类
const isMap = ref(1)
const targetPoints = ref([])
const activeType = ref({})
const needShowColor = ref({})

const switchType = (curItem) => {
  isMap.value = curItem.isMap
  activeType.value = curItem

  // 点击一级分类
  if (curItem.pid === 0) {
    targetPoints.value = curItem.children.reduce(
      (a, c) => [...a, ...c.children],
      []
    )
    addColor(curItem.children)
    needShowColor.value = curItem
  } else {
    // 点击二级分类
    targetPoints.value = curItem.children
  }
  setTimeout(() => {
    window._driving_map?.clearResults()
    map.centerAndZoom('北京市顺义汽车站', 13)
    isMap.value && addMarker(map, targetPoints.value, needShowColor.value)
  }, 400)
}

// 打开信息框(三级分类点击)
const openInfoWindow = (point) => {
  // point.id = null // 破坏一级二级高亮判断（目的让三级分类高亮）
  activeType.value = point
  // 找到所有marker 触发自定义事件
  const markers = map.getOverlays()
  markers.forEach((marker) => {
    if (marker.id === point.id) {
      marker.clickEvent()
    }
  })
}

const isCollapse = ref(true)

// 绘制地图
let map = null
onMounted(async () => {
  map = initMap('container')
  await getBoundary(map)
  setTimeout(() => loadingInstance.close(), 2000)

  getPointsAll()
})
</script>

<template>
  <div class="map-container">
    <div class="left-nav" v-show="isCollapse">
      <!-- 隐患类别分类 -->
      <el-menu text-color="#ccc" background-color="#000c17" :unique-opened="true">
        <el-sub-menu :index="item.id.toString()" v-for="item, subIndex in typeList" :key="item.id">
          <template #title>
            <span class="left-tab" @click="switchType(item)" :class="activeType.id === item.id && activeType.ord && 'activeTab'">{{
              item.name }} {{ item.arr?.length }}</span>
          </template>

          <el-sub-menu v-for="subTtem in item.children" :key="subTtem.id" :index="subTtem.id.toString()">
            <template #title>
              <span class="left-tab" @click="switchType(subTtem)"
                :class="activeType.id === subTtem.id && activeType.ord && 'activeTab'">{{ subTtem.name }} {{ subTtem.children.length
                }}</span>
            </template>
            <el-menu-item v-for="point, index in subTtem.children" @click="openInfoWindow(point)">
              <span class="point_name"
                :class="activeType.pointName + activeType.column1 === point.pointName + point.column1 && 'activeTab'">
                <!-- {{ index + 1 }}. {{ point.pointName.slice(0, 8) + '...' }} -->
                {{ index + 1 }}. {{ point.pointName }}
              </span>
            </el-menu-item>
          </el-sub-menu>
        </el-sub-menu>
      </el-menu>
    </div>
    <div class="right-container" v-if="isMap === 1">
      <div id="container" class="map-main"></div>
      <div class="collapse-box">
        <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
          <el-radio-button :value="true">展开</el-radio-button>
          <el-radio-button :value="false">收起</el-radio-button>
        </el-radio-group>
      </div>
      <div class="level-box">
        <ul>
          <li v-for="(type, index) in needShowColor.children" :style="{ backgroundColor: type?.color }"
            class="color-box">
            {{ type.name }}
          </li>
        </ul>
      </div>
    </div>
    <div class="right-container map" v-if="isMap !== 1">
      <!-- <img src="" alt="" style="width: 100%;"> -->
    </div>
  </div>
</template>

<style scoped lang="scss">
.map-container {
  width: 100vw;
  height: 100vh;
  display: flex;

  .left-nav {
    overflow-y: auto;
    width: 260px;
    height: 100vh;

    .el-menu {
      min-height: 100%;
    }

    .activeTab {
      color: #ffd04b;
    }

    .left-tab {
      display: inline-block;
      width: 100%;
    }

    .point_name{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }


  }

  .right-container {
    flex: 1;
    position: relative;

    .collapse-box {
      position: absolute;
      bottom: 0px;
      left: 0px;
      z-index: 999;
    }

    .level-box {
      position: absolute;
      bottom: 0px;
      right: 0px;
    }

    .color-box {
      padding: 4px 8px;
      color: #fff;
      text-align: center;
      font-size: 12px;
      padding: 4px;
    }


  }

  .map {
    background: url('@/assets/images/map/drainage_map.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
  }

}
</style>
